const Nunjucks = require('nunjucks')
const Config = require('../config')

function createEnv(path, opts) {
    let autoescape = opts.autoescape === undefined ? true : opts.autoescape
    let noCache = opts.noCache || false
    let watch = opts.watch || false
    let throwOnUndefined = opts.throwOnUndefined || false

    let env = new Nunjucks.Environment(new Nunjucks.FileSystemLoader(path, {
        noCache: noCache,
        watch: watch
    }), {
        autoescape: autoescape,
        throwOnUndefined: throwOnUndefined
    })

    if(opts.filters){
        for(let f in opts.filters){
           env.addFilter(f, opts.filters[f])
        }
    }

    return env
}

let env = createEnv(Config.view, {
    watch: true,
    filters: {
        hex: function (n) {
            return '0x' + n.toString(16);
        }
    }
})

module.exports = (ctx, next) => {
    ctx.render = (view, opts) => {
        return env.render(view, opts)
    }
    next()
} 